package com.humble.humbleojquestionservice.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.humble.humbleojcommon.common.ErrorCode;
import com.humble.humbleojcommon.constant.CommonConstant;
import com.humble.humbleojcommon.exception.BusinessException;
import com.humble.humbleojcommon.exception.ThrowUtils;
import com.humble.humbleojcommon.utils.SqlUtils;
import com.humble.humbleojmodel.model.dto.QuestionSubmit.QuestionSubmitQueryRequest;
import com.humble.humbleojmodel.model.dto.QuestionSubmit.QuestionSubmitRequest;
import com.humble.humbleojmodel.model.entity.QuestionSubmit;
import com.humble.humbleojmodel.model.entity.User;
import com.humble.humbleojmodel.model.enums.QuestionSubmitLanguageEnum;
import com.humble.humbleojmodel.model.enums.QuestionSubmitStatusEnum;
import com.humble.humbleojmodel.model.enums.UserRoleEnum;
import com.humble.humbleojmodel.model.vo.QuestionSubmitVO;
import com.humble.humbleojquestionservice.mapper.QuestionSubmitMapper;
import com.humble.humbleojquestionservice.service.QuestionSubmitService;
import com.humble.humbleojserviceclient.service.UserFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author humble
* @description 针对表【question_submit(题目提交信息)】的数据库操作Service实现
* @createDate 2025-02-25 12:19:44
*/
@Slf4j
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService {

    @Resource
    UserFeignClient userFeignClient;

    @Override
    public Long doQuestionSubmit(QuestionSubmitRequest questionSubmitreQuest, User loginUser) {
        if(loginUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(loginUser.getId());
        questionSubmit.setQuestionId(questionSubmitreQuest.getQuestionId());
        questionSubmit.setLanguage(questionSubmitreQuest.getLanguage());
        questionSubmit.setCode(questionSubmitreQuest.getCode());
        questionSubmit.setStatus(0);
        questionSubmit.setJudgeInfo("{}");
        validQuestionSubmit(questionSubmit,false);
        boolean save = this.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"提交答案时出现错误");
        }
        return questionSubmit.getId();
    }

    @Override
    public void validQuestionSubmit(QuestionSubmit questionSubmit, boolean add) {
     Long id = questionSubmit.getId();
     Long userId = questionSubmit.getUserId();
     Long questionId = questionSubmit.getQuestionId();
     String language = questionSubmit.getLanguage();
     Integer status = questionSubmit.getStatus();
     String judgeInfo = questionSubmit.getJudgeInfo();

        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }


        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(language,judgeInfo), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(language) && QuestionSubmitLanguageEnum.getEnumByValue(language) == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "提交语言有误");
        }
        if (status!=null && QuestionSubmitStatusEnum.getEnumByValue(status) == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "提交状态有误");
        }
        if (StringUtils.isNotBlank(judgeInfo) && judgeInfo.length() > 8157) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题信息过长");
        }

    }


    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {


        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        Long id = questionSubmitQueryRequest.getId();
        Long userId = questionSubmitQueryRequest.getUserId();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        String language = questionSubmitQueryRequest.getLanguage();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id)&&id!=0, "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId)&&questionId!=0, "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId)&&userId!=0, "userId", userId);
        queryWrapper.orderBy(
                SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),sortField
        );
        return queryWrapper;
    }


    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        Long id = loginUser.getId();
        if(loginUser.getUserRole()!= UserRoleEnum.ADMIN.getValue()&&!id.equals(questionSubmit.getUserId())){
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionSubmitList.stream().map(QuestionSubmit::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userFeignClient.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> {
            QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
            Long userId = questionSubmit.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionSubmitVO.setUserVO(userFeignClient.getUserVO(user));
            return questionSubmitVO;
        }).collect(Collectors.toList());
        if(questionSubmitVOList.size()==0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"查询为空");
        }
        questionSubmitVOPage.setRecords(questionSubmitVOList);

        return questionSubmitVOPage;
    }
}




